package com.bdhub.handld;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bdhub.im.server.protobuf.MessageProtobuf.CMsg;

import java.util.Map;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 收取消息
 * @author lp
 *
 */
public class ReadHandler extends SimpleChannelInboundHandler<Object> {
	private ClientBootstrap bootstrap;

	public ReadHandler(ClientBootstrap clientBootstap) {
		this.bootstrap = clientBootstap;
	}

	@Override
	public void channelInactive(ChannelHandlerContext arg) throws Exception {
		arg.channel().close();
		bootstrap.resetConnect();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		// 释放资源
		ctx.close();
	}

	@Override
	protected void channelRead0(ChannelHandlerContext arg0, Object msg)
			throws Exception {
		CMsg m = (CMsg) msg;

		int int_type = m.getHead().getType();
		bootstrap.getProcesser().setLastReadTime(System.currentTimeMillis());
		switch (int_type) {
		case 1000: {
		}
			//
			break;
		case 3001: {
			Map<String, Object> map = JSON.parseObject(m.getHead()
					.getComments(), new TypeReference<Map<String, Object>>() {
			});
			String mid = (String) map.get("mid");
			map.clear();
			map = null;
			bootstrap.getMessageTimeOutManager().removeAndStop(mid);

		}
			break;
		case 3003: {
			Map<String, Object> map = JSON.parseObject(m.getHead()
					.getComments(), new TypeReference<Map<String, Object>>() {
			});
			String mid = (String) map.get("mid");
			map.clear();
			map = null;
			// 关闭定时器
			bootstrap.getMessageTimeOutManager().removeAndStop(mid);
		}
			//
			break;
		}
		bootstrap.getDispatcher().receiveMsg(m);
	}
}
